from app.config import SysConfig
from app.service.driver import Driver
from app.lib.TencentDNS import TencentDNS
from app.functions import *


class Tx(Driver):
    def __init__(self, secret_id, secret_key, domain=""):
        self.DomainName = domain
        self.dnsPod = TencentDNS({
            'secretId': secret_id,
            'secretKey': secret_key
        })

    def addRecord(self, subDomain, recordValue):
        return self.RecordCreate(subDomain, recordValue, 'TXT')

    def cleanRecord(self, subDomain):
        queryRes = self.dnsPod.DescribeRecordList(self.DomainName, {"recordType": "TXT", "subDomain": subDomain})
        status = queryRes.get('status')
        if (status != SysConfig.STATUS_CODE_SUCCESS):
            return queryRes
        records = queryRes.get('data', {}).get('RecordList', [])
        for record in records:
            delRes = self.dnsPod.DeleteRecord(self.DomainName, record['RecordId'])
            if delRes.get('status') != SysConfig.STATUS_CODE_SUCCESS:
                return delRes
        return funReturn(SysConfig.STATUS_CODE_SUCCESS, 'success')

    def RecordCreate(self, subDomain, recordValue, recordType):
        queryRes = self.dnsPod.DescribeRecordList(self.DomainName, {"recordType": recordType, "subDomain": subDomain})
        status = queryRes.get('status')
        if status == SysConfig.STATUS_CODE_SUCCESS:
            listData = queryRes.get('data', {}).get('RecordList', {})
            if listData:
                self.dnsPod.DeleteRecord(self.DomainName, listData[0].get('RecordId'))
        return self.dnsPod.CreateRecord(self.DomainName, subDomain, recordType, recordValue)
